package net.melon.agency.inst.ssh.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.esj.auth.pojo.CoreAdmin;
import net.esj.basic.dao.querybuilder.SymbolExpression;
import net.esj.basic.view.AbstractPluginPageAction;
import net.melon.agency.inst.ssh.service.AuthService;
import net.melon.agency.pojo.AgencyGroup;
import net.melon.agency.pojo.AgencyUser;

public class GroupAction extends AbstractPluginPageAction<AgencyGroup, AgencyGroup> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 227636512943011793L;
	
	@Resource
	private AuthService authService;
	
	@Override
	protected void doQueryPage() {
		if(getOperator().getMType().equals(CoreAdmin.MOBJECT_TYPE)){
			pagination.getSearcher().newColumn("agency", "agency", SymbolExpression.NULL.getKey(), "null");
			pagination = authService.pageGroup(pagination);
		}else{
			AgencyUser user =getSessionUser(AgencyUser.class);
			if(user!=null){
				pagination.setPage(1);
				List<AgencyGroup> list = new ArrayList<AgencyGroup>(user.getGroups());
				pagination.setRows(list);
				pagination.setRp(list.size());
				pagination.setSum(1);
				pagination.setTotal(list.size());
			}
		}
	}

	@Override
	protected void afterQueryPage() {
		for(Object o : pagination.getRows()){
			AgencyGroup ag = (AgencyGroup) o;
			if(ag.getAgency()!=null){
				ag.setAgencyG(1);
			}
		}
		super.afterQueryPage();
	}
	
	@Override
	protected void doAdd() throws Exception {
		if(getNamespace().indexOf("agency")>0){
			AgencyUser user =getSessionUser(AgencyUser.class);
			if(user!=null){
				entity.setAgency(user.getAgency());
				entity.setAgencyUseId(user.getId());
			}
		}
		authService.saveAuthGroupAndResetFuncs(entity);
	}


	@Override
	protected void doUpdate() throws Exception {
		if(getNamespace().indexOf("agency")>0){
			AgencyUser user =getSessionUser(AgencyUser.class);
			if(user!=null){
				entity.setAgency(user.getAgency());
			}
		}
		authService.saveAuthGroupAndResetFuncs(entity);
	}

	@Override
	protected void doDelete() throws Exception {
		entity = new AgencyGroup();
		entity.setId(id);
		authService.deleteGroup(entity);
	}


	@Override
	protected void doLoad() {
		entity = (AgencyGroup) authService.getGroupWithFuncs(id).self;
	}


	public void setEntity(AgencyGroup entity){
		this.entity = entity;
	}
	
	public AgencyGroup getEntity(){
		return this.entity;
	}
}
